﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Space_Conquest
{

    class ChatEntry
    {

        public Player FromWho;
        public string ChatMessage;
        public int TimeToLive;
    
    }

    class ChatManager : IMotion, IRender
    {

        #region Private Members

        GameEngine _parent;

        List<ChatEntry> _chatEntries = new List<ChatEntry>();

        #endregion

        #region Constructors

        public ChatManager(GameEngine parent)
        {

            _parent = parent;

        }

        #endregion

        #region Properties

        public GameEngine Parent
        {
            get
            {
                return _parent;
            }
        }

        #endregion

        #region Methods

        public void DisplayChatMessage(Player player, string message)
        {

            ChatEntry entry = new ChatEntry();

            entry.ChatMessage = message;
            entry.FromWho = player;
            entry.TimeToLive = 200;

            _chatEntries.Add(entry);

        }

        #endregion

        #region IRender Members

        public void Render()
        {

            for (int i = 0; i < _chatEntries.Count; ++i)
            {

                string fullMessage = "";
                if(_chatEntries[i].FromWho != null)
                    fullMessage = _chatEntries[i].FromWho.Name + ": " + _chatEntries[i].ChatMessage;
                else
                    fullMessage = "Game: " + _chatEntries[i].ChatMessage;

                Text.Render(fullMessage, Color.Black, 30 - 2, 62 + (i * 20) - 2);
                Text.Render(fullMessage, (_chatEntries[i].FromWho == null ? Color.White : Player.GetColor(_chatEntries[i].FromWho.ID)), 30, 62 + (i * 20));

            }

        }

        #endregion

        #region IMotion Members

        public void Motion()
        {

            List<ChatEntry> entriesToRemove = new List<ChatEntry>();

            // Decrement TimeToLive, check if entry should still be displayed
            // If TimeToLive == 0, add to temporary list to remove (can't remove in foreach loop directly)
            foreach (ChatEntry entry in _chatEntries)
            {

                entry.TimeToLive--;
                if (entry.TimeToLive == 0)
                {
                    entriesToRemove.Add(entry);
                }

            }

            // Remove all entries where TimeToLive == 0
            foreach (ChatEntry entry in entriesToRemove)
            {

                _chatEntries.Remove(entry);

            }

        }

        #endregion
    }

}
